﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using Dal.Properties;
using Common;

namespace Dal
{
    public class CrawlUrlManager
    {
        SqlConnection _connection;
        SqlDataReader _reader;
        string _connectionString;
        public CrawlUrlManager()
        {
              _connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            if (_connectionString == null)
                _connectionString = Settings1.Default.ConnectionString;
            _connection = new SqlConnection(_connectionString);
            _reader = GetCommandObject().ExecuteReader();
        }

        public CrawlUrlManager(string siteName)
        {
            _connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            if (_connectionString == null)
                _connectionString = Settings1.Default.ConnectionString;
            _connection = new SqlConnection(_connectionString);
            _reader = GetCommandObject(siteName).ExecuteReader();
      
        }

        /// <summary>
        /// Returns null if none.
        /// </summary>
        /// <returns></returns>
        public CrawlUrl GetNextCrawlUrl()
        {
        
            CrawlUrl cu = new CrawlUrl();
            if (_reader.Read())
            {
                cu = new CrawlUrl(new Uri(_reader["url"].ToString()), _reader["site_name"].ToString(),
                    DateTime.Parse(_reader["first_download_date"].ToString()),
                    DateTime.Parse(_reader["last_download_date"].ToString()),
                    (CrawlUrl.CrawlUrlType)Int32.Parse(_reader["ut_id"].ToString()));
            }
            else
            {
                _connection.Close();
                _reader.Close();
                return null;
            }
            return cu;
        }

        SqlCommand GetCommandObject()
        {
            SqlConnection con = new SqlConnection(_connectionString);
            con.Open();
            SqlCommand command = new SqlCommand("get_all_urls", con);
            command.CommandType = System.Data.CommandType.StoredProcedure;
            return command;

        }

        SqlCommand GetCommandObject(string siteName)
        {
            SqlConnection con = new SqlConnection(_connectionString);
            con.Open();
            SqlCommand command = new SqlCommand("get_all_urls_by_site", con);
            command.Parameters.Add(new SqlParameter("@site_name", siteName));
            command.CommandType = System.Data.CommandType.StoredProcedure;
            return command;

        }
    }
}
